<script setup lang="ts">
import type { Props, Emits } from './utils/types'
import { timeAgoFromTimestamp } from '@/utils/index'
import ItemVideo from '@/components/ItemVideo/index.vue'
import { useAuth } from '@/stores/index'
import { ElLoading, ElMessage, ElMessageBox } from 'element-plus'
import APIDetails from '@/api/details'

const $props = withDefaults(defineProps<Props>(), {
    item: {}
})

const $emit = defineEmits<Emits>()

const { isNextOperation } = useAuth()

const $router = useRouter()

function capitalizeFirstLetter(string: string): string {
    if (typeof string !== 'string' || string.length === 0) return string;
    return string.charAt(0).toUpperCase() + string.slice(1);
}

function handleJumpDetails() {
    $router.push({
        name: `${capitalizeFirstLetter($props.item.type)}Details`,
        params: {
            id: $props.item.id
        },
        query: {
            categoryType: capitalizeFirstLetter($props.item.type),
        }
    })
}

const isPlay = shallowRef<boolean>(false)

const audioRef = shallowRef<HTMLAudioElement>()

function formatSeconds(seconds: number): string {
    // 计算分钟和秒钟
    const minutes = Math.floor(seconds / 60);
    const secs = Math.floor(seconds % 60);

    // 格式化为两位数
    const formattedMinutes = String(minutes).padStart(2, '0');
    const formattedSeconds = String(secs).padStart(2, '0');

    return `${formattedMinutes}:${formattedSeconds}`;
}

const time = shallowRef<string>('00:00')

onMounted(() => {
    if (!audioRef.value) return
    audioRef.value?.addEventListener('loadedmetadata', function () {
        time.value = formatSeconds(this.duration)
    })
})

watch(isPlay, (newValue) => {
    if (!audioRef.value) return
    if (newValue) {
        audioRef.value.play()
        startTime()
    } else {
        audioRef.value.pause()
        endTime()
    }
})


let timer: any = null

function startTime() {
    timer = setInterval(() => {
        if (!audioRef.value) return
        const remainingTime = audioRef.value.duration - audioRef.value.currentTime
        if (remainingTime >= 0) {
            time.value = formatSeconds(remainingTime)
        } else {
            isPlay.value = false
        }
    }, 500)

}

function endTime() {
    if (timer) {
        clearInterval(timer)
        timer = null
    }
}

function submitAttention(Invite_code?: string) {
    if (!isNextOperation()) return
    ElMessageBox.confirm(
        '是否关注该店铺？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        if (!Invite_code) return
        const loading = ElLoading.service({ lock: true })
        APIDetails.setUserConcern(Invite_code).then(() => {
            $emit('get-list')
        }).finally(() => {
            loading.close()
        })
    }).catch(() => {
        ElMessage.info('已取消')
    })
}

function submitUnfollow(Invite_code?: string) {
    if (!isNextOperation()) return
    ElMessageBox.confirm(
        '是否取消关注该店铺？',
        '提示',
        {
            confirmButtonText: '确认',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        if (!Invite_code) return
        const loading = ElLoading.service({ lock: true })
        APIDetails.cancelUserConcern(Invite_code).then(() => {
            $emit('get-list')
        }).finally(() => {
            loading.close()
        })
    }).catch(() => {
        ElMessage.info('已取消')
    })
}

function handlePlay() {
    $emit('on-play')
}


function onPlay() {
    isPlay.value = true
}


function handleSuspend() {
    isPlay.value = false
}

defineExpose({
    onPlay,
    handleSuspend,
    item: $props.item
})


</script>

<template>
    <div class="item-square">
        <div class="information">
            <div class="photo">
                <div class="left">
                    <img v-if="item?.user?.head_img" :src="item?.user?.head_img" alt="head_img">
                </div>
                <div class="right">
                    <button type="button" @click="submitAttention(item?.user?.Invite_code)"
                        v-if="item?.user?.is_concern == 0">关注</button>
                    <button type="button" style="background-color: #9499a0;"
                        @click="submitUnfollow(item?.user?.Invite_code)" v-if="item?.user?.is_concern == 1">已关注</button>
                    <p>{{ item?.user?.username }}</p>
                </div>
            </div>
            <div class="time">{{ item?.time && timeAgoFromTimestamp(item?.time) }}</div>
        </div>

        <div class="item-square-content">
            <div class="video" v-if="item.type == 'video'">
                <div class="image" @click="handleJumpDetails">
                    <ItemVideo style="width: 100%; height: 100%;" :image="item.image" :sample="item.sample" />
                </div>
                <div class="text">{{ item.type_name }}</div>
            </div>
            <div class="picture" v-else-if="item.type == 'picture'">
                <div class="image" @click="handleJumpDetails">
                    <img :src="item.image" alt="图片素材">
                </div>
                <div class="text">{{ item.type_name }}</div>
            </div>
            <div class="music" v-else-if="item.type == 'music'">
                <div class="music-content">
                    <div class="music-console" :style="{ backgroundImage: `url(${item.image})` }">
                        <img class="play" src="./images/play.png" alt="play" v-show="!isPlay" @click="handlePlay">
                        <img class="suspend" src="./images/suspend.png" alt="play" v-show="isPlay"
                            @click="handleSuspend">
                    </div>
                    <div class="music-text" @click="handleJumpDetails">
                        <p>{{ item.title }}</p>
                        <p>店主：<span style="color: #009DD8">{{ item.user.username }}</span></p>
                    </div>
                    <div class="music-time">{{ time }}</div>
                    <audio ref="audioRef" style="display: none;" :src="item.sample"></audio>
                </div>
                <div class="text">{{ item.type_name }}</div>
            </div>
            <div class="font" v-else-if="item.type == 'font'">
                <div class="image" @click="handleJumpDetails">
                    <img :src="item.image" alt="字体素材">
                </div>
                <div class="text">{{ item.type_name }}</div>
            </div>
        </div>
    </div>
</template>

<style lang="scss" scoped>
.item-square {
    border-bottom: 1px solid #E8E8E8;
    padding: 14px 0;

    .item-square-content {

        .font {
            display: flex;
            align-items: flex-end;

            .image {

                width: 200px;
                height: 133px;

                img {
                    width: 100%;
                    height: 100%;
                    display: block;
                    border-radius: 5px;
                    cursor: pointer;
                    object-fit: cover;
                }
            }

            .text {
                line-height: 1em;
                font-size: 14px;
                color: #9a9a9a;
                margin-left: 20px;
                font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
            }
        }

        .music {
            display: flex;
            align-items: flex-end;

            .text {
                line-height: 1em;
                font-size: 14px;
                color: #9a9a9a;
                margin-left: 20px;
                font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
            }

            .music-content {
                width: 325px;
                height: 70px;
                background-color: #EFEFEF;
                border-radius: 40px;
                display: flex;
                align-items: center;
                font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
            }

            .music-time {
                margin-left: auto;
                margin-right: 25px;
                color: #28211F;
            }

            .music-text {
                margin-left: 10px;
                color: #28211F;
                cursor: pointer;
            }

            .music-console {
                width: 70px;
                height: 70px;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                background-size: cover;
                background-position: center;

                .suspend {
                    width: 35px;
                    height: 35px;
                    display: block;
                    cursor: pointer;
                }

                .play {
                    width: 30px;
                    height: 30px;
                    display: block;
                    margin-left: 6px;
                    cursor: pointer;
                }
            }
        }

        .picture {
            display: flex;
            align-items: flex-end;

            .image {
                img {
                    height: 168px;
                    display: block;
                    border-radius: 5px;
                    cursor: pointer;
                }
            }

            .text {
                line-height: 1em;
                font-size: 14px;
                color: #9a9a9a;
                margin-left: 20px;
                font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
            }
        }

        .video {
            display: flex;
            align-items: flex-end;

            .image {
                border-radius: 5px;
                height: 168px;
                overflow: hidden;
                width: 300px;

                img {
                    display: block;
                    cursor: pointer;
                }
            }

            .text {
                line-height: 1em;
                font-size: 14px;
                color: #9a9a9a;
                margin-left: 20px;
                font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
            }
        }
    }

    .information {
        display: flex;
        justify-content: space-between;
        margin-bottom: 14px;

        .time {
            color: rgba(206, 206, 206, 1);
            font-size: 14px;
            font-family: 'SOURCEHANSANSCN-EXTRALIGHT';
        }

        .photo {
            display: flex;

            .right {
                margin-left: 15px;

                button {
                    width: 40px;
                    height: 18px;
                    line-height: 18px;
                    border-radius: 5px;
                    background-color: rgba(249, 20, 20, 1);
                    color: rgba(255, 255, 255, 1);
                    font-size: 12px;
                    border: none;
                    cursor: pointer;
                    display: block;
                    margin-top: 6px;
                }

                p {
                    color: rgba(154, 154, 154, 1);
                    font-size: 18px;
                    margin-top: 6px;
                    font-family: 'SOURCEHANSANSCN-LIGHT';
                }
            }

            .left {
                width: 58px;
                height: 58px;
                border-radius: 50%;
                background-color: #E8E8E8;
                overflow: hidden;

                img {
                    width: 100%;
                    height: 100%;
                    object-fit: cover;
                }
            }
        }
    }
}
</style>
